package com.android.happymall.fragment.detail;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.happymall.R;
import com.android.happymall.activity.BaseObject;
import com.android.happymall.activity.DirectBuyPayOrderActivity;
import com.android.happymall.activity.mine.TransparentActivity;
import com.android.happymall.fragment.BaseLazyFragment;
import com.android.happymall.model.detail.DirectBuySubmitOrder;
import com.android.happymall.model.detail.DirectBuySubmitOrderCallback;
import com.android.happymall.model.member.DirectBuyFirmOrderData;
import com.android.happymall.model.member.DirectBuyFirmOrderDataCallback;
import com.android.happymall.utils.ConstantsUrl;
import com.android.happymall.utils.HttpUtils;
import com.android.happymall.utils.MyLog;
import com.android.happymall.utils.ObjectUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static android.app.Activity.RESULT_OK;


/**
 * 直购确认订单页
 */
public class Fragment_DirectBuy_FirmOrder extends BaseLazyFragment {


    @BindView(R.id.firmorder_address_name)
    TextView addressName;
    @BindView(R.id.firmorder_address_phone)
    TextView addressPhone;
    @BindView(R.id.firmorder_address_address)
    TextView addressAddress;
    @BindView(R.id.firmorder_goods_img)
    ImageView goodsImg;
    @BindView(R.id.firmorder_goods_title)
    TextView goodsTitle;
    @BindView(R.id.firmorder_goods_money)
    TextView goodsPrice;
    @BindView(R.id.firmorder_goods_score)
    TextView goodsScore;
    @BindView(R.id.firmorder_bottom_money)
    TextView totalPrice;
    @BindView(R.id.firmorder_bottom_score)
    TextView totalScore;
    @BindView(R.id.scroll)
    ScrollView scroll;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.firmorder_bottom_buy)
    LinearLayout toBuy;
    @BindView(R.id.firmorder_address_add_ll)
    LinearLayout payAddressAddLl;
    @BindView(R.id.firmorder_address_ll)
    LinearLayout payAddressLl;
    @BindView(R.id.firmorder_goods_num)
    TextView goodsNum;
    @BindView(R.id.firmorder_mine_score)
    TextView mineScore;
    @BindView(R.id.firmorder_goods_total_price)
    TextView subTotal;
    @BindView(R.id.firmorder_goodss_total_score)
    TextView subTotalScore;
    @BindView(R.id.firmorder_goods_freight)
    TextView freight;

    private FragmentActivity mcontext;
    private View view;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String goodsid;
    private int qty;
    private String goods_img_src;
    private String goods_buy_num;
    private final int ADD_REQUEST = 1;
    private final int REPLACE_REQUEST = 0;
    private DirectBuyFirmOrderData.DataBean.AddressBean addressData;

    public Fragment_DirectBuy_FirmOrder() {

    }

    public static Fragment_DirectBuy_FirmOrder newInstance(String goodsid, int qty) {
        Fragment_DirectBuy_FirmOrder fragment = new Fragment_DirectBuy_FirmOrder();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, goodsid);
        args.putInt(ARG_PARAM2, qty);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            goodsid = getArguments().getString(ARG_PARAM1);
            qty = getArguments().getInt(ARG_PARAM2);
        }
    }

    @Override
    protected void initPrepare() {
        initUI();
    }

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        getDataOrder(goodsid, qty);
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.fragment_directbuy_firmorder, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        return view;
    }

    private void initUI() {
        scroll.smoothScrollTo(0, 0);
    }

    @OnClick({R.id.firmorder_address_add_ll, R.id.firmorder_address_ll, R.id.firmorder_bottom_buy,
            R.id.rl_mine_score
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.firmorder_address_add_ll:
                Intent intent = new Intent(mcontext, TransparentActivity.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 0);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_NUMBER, 2);
                startActivityForResult(intent, ADD_REQUEST);
                break;
            case R.id.firmorder_address_ll:
                Intent intent_address = new Intent(mcontext, BaseObject.class);
                intent_address.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "选择收货地址");
                startActivityForResult(intent_address, REPLACE_REQUEST);
                break;
            case R.id.firmorder_bottom_buy:
                if (addressData != null && addressData.getId() != null) {
                    submitOrder(addressData.getId());
                } else {
                    ObjectUtils.toast(mcontext, "请添加收货地址");
                }
                break;
            case R.id.rl_mine_score:
                Intent intent_score = new Intent(mcontext, BaseObject.class);
                intent_score.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "积分明细");
                startActivity(intent_score);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REPLACE_REQUEST) {
                String name = data.getStringExtra("name");
                addressName.setText(name);
                String mobile = data.getStringExtra("mobile");
                addressPhone.setText(mobile);
                String area = data.getStringExtra("area");
                String address = data.getStringExtra("address");
                addressAddress.setText(area + address);
                String id = data.getStringExtra("id");
                addAddressData(name, mobile, area, address, id);
            } else {
                getDataOrder(goodsid, qty);
            }
        }
    }

    private void addAddressData(String name, String mobile, String area, String address, String id) {
        addressData = new DirectBuyFirmOrderData.DataBean.AddressBean();
        addressData.setName(name);
        addressData.setMobile(mobile);
        addressData.setArea(area);
        addressData.setAddress(address);
        addressData.setId(id);
    }

    //网络数据
    private void getDataOrder(String id, int qty) {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_FIRMORDER;
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id + "");
        map.put("qty", qty + "");
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HttpUtils.post(address, header, map, dataCallback);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    DirectBuyFirmOrderDataCallback dataCallback = new DirectBuyFirmOrderDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
        }

        @Override
        public void onResponse(DirectBuyFirmOrderData response, int id) {
            if (response.getCode() == 0 && response.getData() != null) {
                DirectBuyFirmOrderData.DataBean data = response.getData();
                if (data.getAddress() != null && data.getAddress().getId() != null) {
                    payAddressLl.setVisibility(View.VISIBLE);
                    payAddressAddLl.setVisibility(View.GONE);
                    addressData = data.getAddress();
                    addressName.setText(addressData.getName());
                    addressPhone.setText(addressData.getMobile());
                    addressAddress.setText(addressData.getArea() + addressData.getAddress());
                } else {
                    //手动创建地址
                    payAddressAddLl.setVisibility(View.VISIBLE);
                    payAddressLl.setVisibility(View.GONE);
                }
                mineScore.setText(data.getFlow_user_score() + "");

                goodsTitle.setText(data.getCart_goods().get(0).getGoods_name());
                //单价和积分
                goodsPrice.setText("¥" + data.getCart_goods().get(0).getGoods_price());
                goodsScore.setText(data.getCart_goods().get(0).getGoods_score() + "积分");

                //总价和积分
                totalPrice.setText("¥" + data.getTotal().getGoods_amount());
                totalScore.setText(data.getTotal().getScore_amout() + "积分");

                //商品部分的总价和积分，运费
                subTotal.setText("¥" + data.getCart_goods().get(0).getSubtotal());
                subTotalScore.setText(data.getCart_goods().get(0).getSubtotal_score() + "");
                freight.setText("+¥" + 0.00);

                goods_buy_num = data.getCart_goods().get(0).getQty();
                goodsNum.setText("x" + goods_buy_num);
                goods_img_src = data.getCart_goods().get(0).getImg_src();
                ObjectUtils.photo(mcontext, goods_img_src, goodsImg);
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            } else {
                if(response.getCode() == 40001){
                    ObjectUtils.reLogin(mcontext);
                }
                noData.setVisibility(View.VISIBLE);
                noDataTv.setText(response.getMsg());
                noDataTv.setVisibility(View.VISIBLE);
            }
        }
    };

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        getDataOrder(goodsid, qty);
    }

    //提交订单获取订单编号
    private void submitOrder(String addressId) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_SUBMITORDER;
        HashMap<String, String> map = new HashMap<>();
        map.put("address_id", addressId + "");
        map.put("ajax", "1");

        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HttpUtils.post(address, header, map, orderCallback);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    DirectBuySubmitOrderCallback orderCallback = new DirectBuySubmitOrderCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }

        @Override
        public void onResponse(DirectBuySubmitOrder response, int id) {
            if (response != null && !response.equals("") && response.getError() == 0 && response.getData() != null) {
                String order_sn = response.getData().getOrder_sn();
                Intent intent = new Intent(mcontext, DirectBuyPayOrderActivity.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_ORDER_ID, order_sn);
                mcontext.startActivity(intent);
                getActivity().finish();
            } else {
                if(response != null && !response.equals("")){
                    ObjectUtils.toast(mcontext, response.getMsg());
                }
            }
        }
    };
}
